<?php
include __DIR__ . '/config/database.config.php';

class DB
{
    private $conn;

    public function __construct()
    {
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE, DB_PORT);
        if ($this->conn->connect_error) {
            # 数据库连接错误
            die("数据库连接失败: " . $this->conn->connect_error);
        }
        $this->conn->set_charset(DB_CHAR);
    }

    public function __destruct()
    {
        $this->conn->close();
    }

    public function execute($sql)
    {
        $result = $this->conn->query($sql);
        if ($result and $this->conn->affected_rows > 0) {
            return true;
        } else if ($result and $this->conn->affected_rows == 0) {
            return false;
        } else {
            // 返回数据库错误语句
            echo $this->conn->error;
            return false;
        }
    }

    public function selectAll($sql)
    {
        $result = $this->conn->query($sql);
        $data = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                array_push($data, $row);
            }
            return $data;
        } else {
            // 返回数据库错误语句
            echo $this->conn->error;
            return false;
        }
    }

    public function selectOne($sql)
    {
        $result = $this->conn->query($sql);
        $data = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $data = $row;
            }
            return $data;
        } else {
            // 返回数据库错误语句
            echo $this->conn->error;
            return false;
        }
    }
}
